package cn.zn.modules.money.his.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.modules.money.enums.MoneyTypeEnum;
import cn.zn.modules.money.his.entity.MoneyInfoSum;
import cn.zn.modules.money.his.entity.QMoneyInfoSum;
import cn.zn.modules.money.his.entity.dto.MoneyInfoSumDTO;
import cn.zn.modules.money.his.entity.vo.MoneyInfoSumVO;
import cn.zn.modules.money.his.repository.MoneyInfoSumRepository;
import cn.zn.modules.money.his.service.MoneyInfoSumService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;


@Service("moneyInfoSumService")
public class MoneyInfoSumServiceImpl implements MoneyInfoSumService {

    @Autowired
    private MoneyInfoSumRepository moneyInfoSumRepository;

    @Override
    public List<MoneyInfoSumVO> findSum(MoneyInfoSumDTO moneyInfoSumDTO) {
        QMoneyInfoSum qMoneyInfoSum = QMoneyInfoSum.moneyInfoSum;
        Predicate predicate = qMoneyInfoSum.isNotNull().or(qMoneyInfoSum.isNull());
        if (moneyInfoSumDTO.getAp() != null) {
            predicate = ExpressionUtils.and(predicate, qMoneyInfoSum.ap.eq(moneyInfoSumDTO.getAp()));
        }
        if (moneyInfoSumDTO.getMoneyTypeCode() != null) {
            predicate = ExpressionUtils.and(predicate, qMoneyInfoSum.moneyTypeCode.eq(moneyInfoSumDTO.getMoneyTypeCode()));
        }
        if (StrUtil.isNotBlank(moneyInfoSumDTO.getProjectName())) {
            predicate = ExpressionUtils.and(predicate, qMoneyInfoSum.projectName.like("%" + moneyInfoSumDTO.getProjectName().trim() + "%"));
        }
        if (StrUtil.isNotBlank(moneyInfoSumDTO.getCateName())) {
            predicate = ExpressionUtils.and(predicate, qMoneyInfoSum.cateName.like("%" + moneyInfoSumDTO.getCateName().trim() + "%"));
        }
        Iterator<MoneyInfoSum> moneyInfoSumIterator = moneyInfoSumRepository.findAll(predicate).iterator();
        List<MoneyInfoSumVO> moneyInfoSumVOS = CollUtil.newArrayList();
        MoneyInfoSum moneyInfoSum;
        MoneyInfoSumVO moneyInfoSumVO;
        while (moneyInfoSumIterator.hasNext()) {
            moneyInfoSum = moneyInfoSumIterator.next();
            moneyInfoSumVO = new MoneyInfoSumVO();
            BeanUtils.copyProperties(moneyInfoSum, moneyInfoSumVO);
            moneyInfoSumVO.setMoneyTypeName(MoneyTypeEnum.findByCode(moneyInfoSum.getMoneyTypeCode()).getName());
            moneyInfoSumVOS.add(moneyInfoSumVO);
        }
        return moneyInfoSumVOS;
    }
}